<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>发布订阅模式</h1>

<script>
    /*
    * publish 发布
    * subscribe 订阅
    * */

    // 中央调度中心
    let sub = {
        message:{},
        // 发布
        publish(type,data){
            if(!this.message[type]) return
            this.message[type].forEach((item)=>{
                item(data)
            })
        },
        // 订阅
        subscribe(type,cb){
            if(!this.message[type]){
                this.message[type] = [cb]
            }else{
                this.message[type].push(cb)
            }
        },
        // 删除
        unSubscribe(type,cb){
            if(!this.message[type]) return
            // 如果不传 回调的参数 就取消所有的
            if(!cb){
                this.message[type] = []
            }else{
                this.message[type].filter((item=>{
                    return item != cb
                }))
            }
        }
    }
    function testA(data){
        console.log('testa',data)
    }
    function testB(data){
        console.log('testb',data)
    }
    function testC(data){
        console.log('testc',data)
    }
    sub.subscribe('a',testA)
    sub.subscribe('b',testB)
    sub.subscribe('a',testC)

    sub.publish('a',111)

</script>

</body>
</html>
